<template>
  <el-dialog
    v-model="dialogVisible"
    width="1000px"
    :before-close="handleClose"
    destroy-on-close
    class="detection-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <!-- 弹窗头部 -->
    <template #header>
      <div class="dialog-header">
        <div class="header-content">
          <div class="header-icon">
            <el-icon :size="32">
              <Search />
            </el-icon>
          </div>
          <div class="header-text">
            <h3 class="header-title">{{ title }}</h3>
            <p class="header-subtitle">配置冲突检测的基本参数</p>
          </div>
        </div>
      </div>
    </template>

    <!-- 弹窗主体 -->
    <div class="dialog-body">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="detection-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-header">
            <el-icon class="section-icon">
              <InfoFilled />
            </el-icon>
            <span class="section-title">检测配置</span>
          </div>
          
          <div class="form-grid">
            <!-- 检索关键词 -->
                         <!-- 检索范围 -->
             <div class="form-item">
               <div class="form-label">
                 <el-icon><Search /></el-icon>
                 检索范围
              
               </div>
               <el-tree-select
                 v-model="form.scope"
                 :data="enterpriseCategories"
                 placeholder="请选择企业知识库分类"
                 style="width: 100%"
                 class="scope-tree-select"
                 :props="{ label: 'type_name', value: 'id', children: 'children' }"
                 node-key="id"
                 filterable
                 multiple
                 show-checkbox
                 clearable
                 @check="onTreeCheck"
               />
             </div>
           </div>
         </div>

         <!-- 知识库数据表格 -->
         <div class="form-section" v-if="form.scope && form.scope.length > 0">
           <div class="section-header">
             <el-icon class="section-icon">
               <Document />
             </el-icon>
             <span class="section-title">知识库数据</span>
             <span class="section-subtitle">已选择 {{ selectedKnowledgeCount }} 个文件</span>
             <span class="section-debug" v-if="selectedKnowledgeCount > 0">
               (跨页选择已保持)
             </span>
           </div>
           
           <div class="knowledge-table-container">
             <el-table
               ref="knowledgeTableRef"
               :data="paginatedKnowledgeData"
               style="width: 100%"
               height="300"
               @selection-change="handleKnowledgeSelectionChange"
               @select-all="handleSelectAll"
               class="knowledge-table"
             >
               <el-table-column type="selection" width="55" />
               <el-table-column prop="preview_img" label="缩略图" width="80">
                <template #default="scope">
              <el-image
                :src="scope.row.preview_img"
                style="width: 40px; height: 40px"
                fit="cover"
                :preview-src-list="[scope.row.preview_img]"
              />
            </template>
               </el-table-column>
               <el-table-column prop="documentName" label="文档名称" min-width="200" />
               <el-table-column prop="category" label="所属分类" width="150" />
               <el-table-column prop="documentType" label="文档类型" width="100" />
               <el-table-column prop="uploader" label="上传者" width="100" />
               <el-table-column prop="createTime" label="创建时间" width="150">
                 <template #default="{ row }">
                   <span>{{ formatCreateTime(row.createTime) }}</span>
                 </template>
               </el-table-column>
               <el-table-column label="标签" width="200">
                 <template #default="{ row }">
                   <div class="tags-container">
                     <template v-if="parseStringifiedArray(row.label || row.tags).length > 0">
                       <el-tag 
                         v-for="(tag, index) in parseStringifiedArray(row.label || row.tags).slice(0, 3)" 
                         :key="index"
                         size="small"
                         class="tag-item"
                       >
                         {{ tag }}
                       </el-tag>
                       <span 
                         v-if="parseStringifiedArray(row.label || row.tags).length > 3" 
                         class="more-tag"
                       >
                         +{{ parseStringifiedArray(row.label || row.tags).length - 3 }}
                       </span>
                     </template>
                     <span v-else class="no-data">-</span>
                   </div>
                 </template>
               </el-table-column>
               <el-table-column label="关键词" width="200">
                 <template #default="{ row }">
                   <div class="keywords-container">
                     <template v-if="parseStringifiedArray(row.knowledge_keyword || row.keywords).length > 0">
                       <el-tag 
                         v-for="(keyword, index) in parseStringifiedArray(row.knowledge_keyword || row.keywords).slice(0, 3)" 
                         :key="index"
                         size="small"
                         type="info"
                         class="tag-item"
                       >
                         {{ keyword }}
                       </el-tag>
                       <span 
                         v-if="parseStringifiedArray(row.knowledge_keyword || row.keywords).length > 3" 
                         class="more-tag"
                       >
                         +{{ parseStringifiedArray(row.knowledge_keyword || row.keywords).length - 3 }}
                       </span>
                     </template>
                     <span v-else class="no-data">-</span>
                   </div>
                 </template>
               </el-table-column>
             </el-table>
             
             <!-- 分页组件 -->
             <div class="knowledge-pagination" v-if="knowledgeTableData.length > 0">
               <el-pagination
                 v-model:current-page="knowledgeCurrentPage"
                 v-model:page-size="knowledgePageSize"
                 :page-sizes="[5, 10, 20, 50]"
                 :total="knowledgeTableData.length"
                 layout="total, sizes, prev, pager, next"
                 @size-change="handleKnowledgeSizeChange"
                 @current-change="handleKnowledgeCurrentChange"
                 small
               />
             </div>
           </div>
         </div>
      </el-form>
    </div>

    <!-- 弹窗底部 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" class="submit-btn">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  Search, 
  InfoFilled,
  Key,
  Document
} from '@element-plus/icons-vue'
import { getOrgKnowledgeCategory, getKnowledgeByList, type KnowledgeListParams } from '@/api/knowledge/api'
import { addCheckTask, type AddCheckTaskParams } from '@/api/conflictDetection'
import { formatCreateTime } from '@/utils/dateFormat'

// 解析字符串化数组的工具函数
const parseStringifiedArray = (value: string[] | string | undefined): string[] => {
  if (!value) return []
  if (Array.isArray(value)) return value
  if (typeof value === 'string') {
    try {
      // 尝试解析JSON格式的字符串
      const parsed = JSON.parse(value)
      return Array.isArray(parsed) ? parsed : []
    } catch {
      // 如果不是JSON格式，尝试解析类似 "['item1', 'item2']" 的格式
      const match = value.match(/\[(.*)\]/)
      if (match) {
        const items = match[1].split(',').map(item => 
          item.trim().replace(/['"]/g, '')
        ).filter(item => item)
        return items
      }
      // 如果都不匹配，返回空数组
      return []
    }
  }
  return []
}

interface DetectionForm {
  keywords: string[]
  scope: string[]
  selectedKnowledge: string[]
}

interface KnowledgeItem {
  id: string
  documentName: string
  category: string
  documentType: string
  uploader: string
  createTime: string
  preview_img: string
  // 企业知识库字段映射
  filename?: string
  chineseName?: string
  fileType?: string
  file_name?: string
  document_type?: string
  create_time?: string
  // 关键词和标签字段
  label?: string[] | string
  knowledge_keyword?: string[] | string
  tags?: string[] | string
  keywords?: string[] | string
}

interface Props {
  visible: boolean
  title: string
  formData: Partial<DetectionForm>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: DetectionForm): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const knowledgeTableRef = ref()
const loading = ref(false)

// 表单数据
const form = ref<DetectionForm>({
  keywords: [],
  scope: [],
  selectedKnowledge: []
})

// 知识库表格数据
const knowledgeTableData = ref<KnowledgeItem[]>([])

// 选中的知识库项目（存储所有页面的选中状态）
const selectedKnowledgeItems = ref<KnowledgeItem[]>([])

// 已选择的知识库数量
const selectedKnowledgeCount = computed(() => selectedKnowledgeItems.value.length)

// 当前页面的选中状态（用于表格显示）
const currentPageSelection = ref<KnowledgeItem[]>([])

// 知识库分页相关
const knowledgeCurrentPage = ref(1)
const knowledgePageSize = ref(10)

// 分页后的知识库数据
const paginatedKnowledgeData = computed(() => {
  const start = (knowledgeCurrentPage.value - 1) * knowledgePageSize.value
  const end = start + knowledgePageSize.value
  return knowledgeTableData.value.slice(start, end)
})

// 预设关键词
const suggestedKeywords = ref([
  '会议纪要',
  '项目通知',
  '调休制度',
  '规范标准',
  '培训资料',
  '技术文档',
  '操作手册',
  '安全规程',
  '施工规范',
  '设计规范',
  '国家标准',
  '行业标准',
  '地方标准',
  '技术交底',
  '质量要求',
  '验收标准'
])

// 企业分类数据
const enterpriseCategories = ref<any[]>([])

// 将扁平化的分类数据转换为树形结构
const buildTreeFromFlatData = (flatData: any[]) => {
  // 创建ID到节点的映射
  const nodeMap = new Map()
  flatData.forEach(category => {
    nodeMap.set(category.id, {
      ...category,
      children: []
    })
  })
  
  // 构建树形结构
  const tree: any[] = []
  flatData.forEach(category => {
    const node = nodeMap.get(category.id)
    if (category.parent_id === null) {
      // 根节点
      tree.push(node)
    } else {
      // 子节点
      const parent = nodeMap.get(category.parent_id)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  
  return tree
}

// 获取企业知识库分类数据
const fetchEnterpriseCategories = async () => {
  try {
    const result = await getOrgKnowledgeCategory()
    // 确保返回的数据是数组格式，如果不是则包装成数组
    if (Array.isArray(result)) {
      // 将扁平化数据转换为树形结构
      enterpriseCategories.value = buildTreeFromFlatData(result)
    } else {
      enterpriseCategories.value = buildTreeFromFlatData([result])
    }
    console.log('获取企业知识库分类成功:', enterpriseCategories.value)
  } catch (error) {
    console.error('获取企业知识库分类失败:', error)
    // 如果API调用失败，使用默认数据
    enterpriseCategories.value = []
  }
}

// 表单验证规则
const rules: FormRules = {
  keywords: [
    { required: true, message: '请选择或输入检索关键词', trigger: 'change' }
  ],
  scope: [
    { required: true, message: '请选择检索范围', trigger: 'change' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData && Object.keys(newData).length > 0) {
      form.value = {
        keywords: newData.keywords || [],
        scope: newData.scope || [],
        selectedKnowledge: newData.selectedKnowledge || []
      }
    } else {
      // 重置表单
      form.value = {
        keywords: [],
        scope: [],
        selectedKnowledge: []
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听检索范围变化
watch(
  () => form.value.scope,
  (newScope) => {
    if (newScope && newScope.length > 0) {
      loadKnowledgeData()
    } else {
      knowledgeTableData.value = []
      selectedKnowledgeItems.value = []
    }
  }
)

// 树形选择器检查事件
const onTreeCheck = (data: any, checkedInfo: any) => {
  console.log('树形选择器检查事件:', data, checkedInfo)
  // 当选择分类变化时，加载对应的知识库数据
  loadKnowledgeData()
}

// 加载知识库数据
const loadKnowledgeData = async () => {
  if (!form.value.scope || form.value.scope.length === 0) {
    knowledgeTableData.value = []
    return
  }

  try {
    // 保存当前的选中状态，用于数据刷新后恢复
    const currentSelectedIds = selectedKnowledgeItems.value.map(item => item.id)
    
    // 调用企业知识库列表接口
    const params: KnowledgeListParams = {
      page: 1,
      page_size: 100, // 获取更多数据用于分页
      file_category: form.value.scope.join(',') // 将选中的分类ID作为参数
    }
    
    const response:any = await getKnowledgeByList(params)
    console.log('企业知识库列表API响应:', response)
    
    // 转换API返回的数据格式
const apiData = response?.items || []
const convertedData: KnowledgeItem[] = apiData.map((item: any) => ({
  id: item.id,
  documentName: item.filename || item.file_name || item.chineseName || '未知文档',
  category: item.file_category_name  || '未知分类',
  documentType: item.document_type_name
  || '未知类型',
  uploader: item.uploader || '未知上传者',
  createTime: item.createTime || item.create_time || '未知时间',
  preview_img: item.preview_img || '加载失败',
  // 保留原始字段用于兼容
  filename: item.filename || item.file_name,
  chineseName: item.chineseName,
  fileType: item.fileType,
  file_name: item.file_name,
  document_type: item.document_type,
  create_time: item.create_time,
  // 关键词和标签字段
  label: item.label,
  knowledge_keyword: item.knowledge_keyword,
  tags: item.tags,
  keywords: item.keywords
}))

    knowledgeTableData.value = convertedData
    // 重置分页状态
    knowledgeCurrentPage.value = 1
    console.log('加载知识库数据成功:', convertedData)
    
    // 恢复之前选中的状态（如果数据仍然存在）
    if (currentSelectedIds.length > 0) {
      // 找到仍然存在的数据并恢复选中状态
      const stillExistingItems = selectedKnowledgeItems.value.filter(item => 
        currentSelectedIds.includes(item.id) && 
        convertedData.some(newItem => newItem.id === item.id)
      )
      selectedKnowledgeItems.value = stillExistingItems
      form.value.selectedKnowledge = stillExistingItems.map(item => item.id)
    }
    
    // 设置当前页的选中状态
    nextTick(() => {
      setCurrentPageSelection()
    })
  } catch (error) {
    console.error('加载知识库数据失败:', error)
    knowledgeTableData.value = []
    // 重置分页状态
    knowledgeCurrentPage.value = 1
  }
}

// 知识库表格选择变化事件
const handleKnowledgeSelectionChange = (selection: KnowledgeItem[]) => {
  // 更新全局选中状态
  updateGlobalSelection(selection)
  console.log('选中的知识库项目:', selectedKnowledgeItems.value)
}

// 知识库分页大小改变
const handleKnowledgeSizeChange = (size: number) => {
  knowledgePageSize.value = size
  knowledgeCurrentPage.value = 1
  // 重新设置当前页的选中状态
  nextTick(() => {
    setCurrentPageSelection()
  })
}

// 知识库当前页改变
const handleKnowledgeCurrentChange = (page: number) => {
  knowledgeCurrentPage.value = page
  // 重新设置当前页的选中状态
  nextTick(() => {
    setCurrentPageSelection()
  })
}

// 设置当前页的选中状态
const setCurrentPageSelection = () => {
  if (!knowledgeTableRef.value) return
  
  // 清空当前表格的选中状态
  knowledgeTableRef.value.clearSelection()
  
  // 获取当前页的数据
  const currentPageData = paginatedKnowledgeData.value
  
  // 遍历当前页数据，检查是否在全局选中列表中
  currentPageData.forEach((item, index) => {
    const isSelected = selectedKnowledgeItems.value.some(selected => selected.id === item.id)
    if (isSelected) {
      // 如果当前项在全局选中列表中，则选中它
      knowledgeTableRef.value.toggleRowSelection(item, true)
    }
  })
}

// 更新全局选中状态
const updateGlobalSelection = (currentPageSelection: KnowledgeItem[]) => {
  // 获取当前页的所有数据ID
  const currentPageIds = paginatedKnowledgeData.value.map(item => item.id)
  
  // 从全局选中列表中移除当前页的数据（因为当前页的选中状态会重新设置）
  selectedKnowledgeItems.value = selectedKnowledgeItems.value.filter(item => 
    !currentPageIds.includes(item.id)
  )
  
  // 将当前页的选中数据添加到全局选中列表
  selectedKnowledgeItems.value.push(...currentPageSelection)
  
  // 更新表单数据
  form.value.selectedKnowledge = selectedKnowledgeItems.value.map(item => item.id)
}

// 处理全选/取消全选
const handleSelectAll = (selection: KnowledgeItem[]) => {
  // 如果当前页全选了，则将当前页所有数据添加到全局选中列表
  if (selection.length === paginatedKnowledgeData.value.length) {
    // 从全局选中列表中移除当前页的数据
    selectedKnowledgeItems.value = selectedKnowledgeItems.value.filter(item => 
      !paginatedKnowledgeData.value.some(pageItem => pageItem.id === item.id)
    )
    // 添加当前页所有数据
    selectedKnowledgeItems.value.push(...paginatedKnowledgeData.value)
  } else {
    // 如果取消全选，则从全局选中列表中移除当前页的数据
    selectedKnowledgeItems.value = selectedKnowledgeItems.value.filter(item => 
      !paginatedKnowledgeData.value.some(pageItem => pageItem.id === item.id)
    )
  }
  
  // 更新表单数据
  form.value.selectedKnowledge = selectedKnowledgeItems.value.map(item => item.id)
  console.log('全选/取消全选后的选中项目:', selectedKnowledgeItems.value)
}

// 监听分页数据变化，重新设置选中状态
watch(paginatedKnowledgeData, () => {
  nextTick(() => {
    setCurrentPageSelection()
  })
}, { deep: true })

// 组件挂载时获取企业知识库分类数据
onMounted(() => {
  fetchEnterpriseCategories()
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 调用新增冲突检测接口
    const params: AddCheckTaskParams = {
      tid: form.value.selectedKnowledge, // 选中的知识库文件ID，直接传数组
      file_category: form.value.scope.join(',') // 选中的分类ID，用逗号分隔
    }
    
    // 调用实际的API
    await addCheckTask(params)
    console.log('新增冲突检测成功')
    
    const submitData: DetectionForm = {
      keywords: form.value.keywords,
      scope: form.value.scope,
      selectedKnowledge: form.value.selectedKnowledge
    }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  emit('cancel')
}
</script>

<style scoped>
/* 弹窗整体样式 */
.detection-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

/* 标签和关键词容器样式 */
.tags-container,
.keywords-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  min-height: 24px;
}

.tag-item {
  margin: 0;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.more-tag {
  font-size: 11px;
  color: #909399;
  margin-left: 4px;
  cursor: pointer;
}

.no-data {
  color: #c0c4cc;
  font-size: 12px;
}

/* 表格样式优化 */
.knowledge-table :deep(.el-table__header) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
}

.knowledge-table :deep(.el-table__header th) {
  background: transparent;
  color: #4338ca;
  font-weight: 600;
  font-size: 13px;
}

.knowledge-table :deep(.el-table__body td) {
  padding: 8px 0;
  font-size: 12px;
}

.knowledge-table :deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

.detection-dialog :deep(.el-dialog) {
  background: #ffffff;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.detection-dialog :deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.detection-dialog :deep(.el-dialog__body) {
  padding: 0;
  flex: 1;
  overflow-y: auto;
  height: calc(90vh - 120px);
}

.detection-dialog :deep(.el-dialog__footer) {
  padding: 0;
}

.detection-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.3s ease;
}

.detection-dialog :deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.detection-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  font-size: 18px;
  font-weight: bold;
}

/* 弹窗头部样式 */
.dialog-header {
  padding: 12px 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
}

.header-text {
  flex: 1;
}

.header-title {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
}

.header-subtitle {
  margin: 0;
  font-size: 14px;
}

/* 弹窗主体样式 */
.dialog-body {
  background: #f8fafc;
}

.detection-form {
  max-width: 100%;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 10px;
  background: white;
  border-radius: 16px;
  padding: 12px 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: 1px solid #f1f5f9;
  position: relative;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f1f5f9;
}

.section-icon {
  font-size: 20px;
  color: #667eea;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.section-subtitle {
  font-size: 12px;
  color: #6b7280;
  margin-left: auto;
}

.section-debug {
  font-size: 11px;
  color: #10b981;
  margin-left: 8px;
  font-style: italic;
}

/* 表单网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  align-items: start;
}

.form-grid .el-form-item {
  margin-bottom: 0;
}

/* 单列表单项 */
.form-single {
  grid-column: 1 / -1;
}

/* 表单项样式 */
.form-item {
  margin-bottom: 24px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.form-label-note {
  font-size: 12px;
  color: #6b7280;
  font-weight: normal;
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

/* 增强的表单项样式 */
.form-item-enhanced {
  margin-bottom: 24px;
}

.form-item-enhanced :deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.form-item-enhanced :deep(.el-input) {
  height: 44px;
}

.form-item-enhanced :deep(.el-textarea) {
  height: auto;
}

.form-item-enhanced :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  padding: 0 16px;
  height: 44px;
}

.form-item-enhanced :deep(.el-textarea .el-textarea__inner) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  padding: 12px 16px;
  min-height: 80px;
}

.form-item-enhanced :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-textarea .el-textarea__inner:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-textarea .el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
}

.form-item-enhanced :deep(.el-select) {
  width: 100%;
}

/* 关键词选择器样式 */
.keywords-select :deep(.el-select__tags) {
  max-width: calc(100% - 30px);
}

.keywords-select :deep(.el-tag) {
  margin: 2px 4px 2px 0;
  background: #f3f0ff;
  border-color: #a685ff;
  color: #a685ff;
}

/* 树形选择器样式 */
.scope-tree-select :deep(.el-tree-select__popper) {
  max-height: 300px;
  overflow-y: auto;
}

.scope-tree-select :deep(.el-tree-node__content) {
  height: 32px;
  line-height: 32px;
}

.scope-tree-select :deep(.el-tree-node__label) {
  font-size: 14px;
}

/* 树形选择器勾选框样式 - 改为紫色 */
.scope-tree-select :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

.scope-tree-select :deep(.el-checkbox__input.is-checked .el-checkbox__inner::after) {
  border-color: #ffffff !important;
}

.scope-tree-select :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

.scope-tree-select :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner::after) {
  background-color: #ffffff !important;
}

.scope-tree-select :deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #a685ff !important;
}

.scope-tree-select :deep(.el-checkbox__input:hover .el-checkbox__inner) {
  border-color: #a685ff !important;
}

/* 全局覆盖树形选择器下拉面板中的勾选框样式 */
:global(.el-tree-select__popper .el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

:global(.el-tree-select__popper .el-checkbox__input.is-checked .el-checkbox__inner::after) {
  border-color: #ffffff !important;
}

:global(.el-tree-select__popper .el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

:global(.el-tree-select__popper .el-checkbox__input.is-indeterminate .el-checkbox__inner::after) {
  background-color: #ffffff !important;
}

:global(.el-tree-select__popper .el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #a685ff !important;
}

:global(.el-tree-select__popper .el-checkbox__input:hover .el-checkbox__inner) {
  border-color: #a685ff !important;
}

/* 知识库表格样式 */
.knowledge-table-container {
  margin-top: 16px;
}

.knowledge-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 知识库分页样式 */
.knowledge-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  padding: 12px 0;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
}

.knowledge-pagination :deep(.el-pagination) {
  margin: 0;
}

.knowledge-pagination :deep(.el-pagination .el-pager li) {
  background: transparent;
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.2s;
}

.knowledge-pagination :deep(.el-pagination .el-pager li:hover) {
  background: #f3f4f6;
}

.knowledge-pagination :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.knowledge-pagination :deep(.el-pagination .btn-prev),
.knowledge-pagination :deep(.el-pagination .btn-next) {
  border-radius: 6px;
  transition: all 0.2s;
}

.knowledge-pagination :deep(.el-pagination .btn-prev:hover),
.knowledge-pagination :deep(.el-pagination .btn-next:hover) {
  background: #f3f4f6;
}

.knowledge-table :deep(.el-table__header) {
  background: #f8fafc;
}

.knowledge-table :deep(.el-table__header th) {
  background: #f8fafc;
  color: #374151;
  font-weight: 600;
  font-size: 14px;
}

.knowledge-table :deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

.knowledge-table :deep(.el-table__row:hover) {
  background: #f8fafc;
}

.knowledge-table :deep(.el-table__row.current-row) {
  background: #f3f0ff !important;
}

.knowledge-table :deep(.el-table__row.current-row:hover) {
  background: #e9e5ff !important;
}

.knowledge-table :deep(.el-table__row.is-selected) {
  background: #f3f0ff !important;
}

.knowledge-table :deep(.el-table__row.is-selected:hover) {
  background: #e9e5ff !important;
}

/* 勾选框样式 - 改为紫色 */
.knowledge-table :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

.knowledge-table :deep(.el-checkbox__input.is-checked .el-checkbox__inner::after) {
  border-color: #ffffff !important;
}

.knowledge-table :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

.knowledge-table :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner::after) {
  background-color: #ffffff !important;
}

.knowledge-table :deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #a685ff !important;
}

.knowledge-table :deep(.el-checkbox__input:hover .el-checkbox__inner) {
  border-color: #a685ff !important;
}

.preview_img-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

.preview_img-error {
  font-size: 12px;
  color: #6b7280;
  background: #f3f4f6;
  padding: 4px 8px;
  border-radius: 4px;
}

.preview_img-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.form-item-enhanced :deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
}

/* 弹窗底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 12px 32px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
}

.cancel-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  background: #f1f5f9;
  border: 1px solid #d1d5db;
  color: #6b7280;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
  transform: translateY(-1px);
}

.submit-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

:deep(.el-dialog__body) {
  height: calc(90vh - 120px);
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detection-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .dialog-header {
    padding: 12px 20px;
  }

  .header-title {
    font-size: 18px;
  }

  .dialog-body {
    padding: 20px;
  }

  .form-section {
    padding: 12px 20px;
    margin-bottom: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .dialog-footer {
    padding: 20px;
    flex-direction: column;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

@media (max-width: 1024px) {
  .detection-dialog :deep(.el-dialog) {
    width: 90% !important;
  }

  .form-grid {
    gap: 20px;
  }
}
</style>
